package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Sets;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description UserServiceImpl
 * @Author luohai
 * @Date 2024-10-24
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final RoleMapper roleMapper;

    private final UserRoleMapper userRoleMapper;

    private final RoleResourceMapper roleResourceMapper;
    @Override
    public PageResponse<UserVo> findUserPage(UserDto userDto, int pageNum, int pageSize) {


        if (!EmptyUtil.isNullOrEmpty(userDto.getDeptNo())) {
            //截取部门编号  100001  dept_no like '100001%'
            userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        }

        PageHelper.startPage(pageNum, pageSize);

        Page<User> page = userMapper.selectPage(userDto);
        PageResponse<UserVo> pageResponse = PageResponse.of(page, UserVo.class);
        if (!EmptyUtil.isNullOrEmpty(pageResponse.getRecords())) {
            List<Long> userIds = pageResponse.getRecords().stream().map(UserVo::getId).collect(Collectors.toList());
            //查询对应角色
            List<RoleVo> roleVoList = roleMapper.findRoleVoListInUserId(userIds);
            //装配数据
            pageResponse.getRecords().forEach(n -> {
                //装配角色
                Set<String> roleVoIds = Sets.newHashSet();
                Set<String> roleVoLabels = Sets.newHashSet();
                roleVoList.forEach(r -> {
                    if (String.valueOf(n.getId()).equals(r.getUserId())) {
                        roleVoIds.add(String.valueOf(r.getId()));
                        roleVoLabels.add(r.getRoleName());
                    }
                });
                n.setRoleLabels(roleVoLabels);
                n.setRoleVoIds(roleVoIds);
            });
        }
        return pageResponse;
    }

    /**
     * 用户添加
     * @param userDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userAddition(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        user.setPassword("123456");
        userMapper.insertSelective(user);
        Set<String> roleVoIds = userDto.getRoleVoIds();
        List<String> roleVoIdsList = roleVoIds.stream().collect(Collectors.toList());
        for (String roleId : roleVoIdsList) {
            UserRole userRole = UserRole.builder().roleId(Long.valueOf(roleId)).userId(user.getId()).build();
            userRoleMapper.insertSelective(userRole);
        }

    }

    /**
     *
     * 用户修改
     * @param userDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userModification(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        Long userId = user.getId();
        userMapper.updateByPrimaryKeySelective(user);
        Set<String> roleVoIds = userDto.getRoleVoIds();
        Integer countByUserId = userRoleMapper.findCountByUserId(userId);
        if (countByUserId>0){
            userRoleMapper.deleteByUserId(String.valueOf(userId));
        }
        List<String> roleVoIdsList = roleVoIds.stream().collect(Collectors.toList());
        for (String roleId : roleVoIdsList) {
            UserRole userRole = UserRole.builder().userId(userId).roleId(Long.valueOf(roleId)).build();
            userRoleMapper.insertSelective(userRole);
        }
    }

    /**
     * 启用或禁用用户
     * @param id
     * @param status
     * @return
     */
    @Override
    public void enableDisable(Long id, String status) {
        User user = userMapper.selectByPrimaryKey(id);
        if (ObjectUtil.isEmpty(user)){
            throw new RuntimeException("用户为空");
        }
        user.setDataState(status);
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 删除用户
     * @param userIds
     * @return
     */
    @Override

    public void deleteUser(String userIds) {
        User user = userMapper.selectByPrimaryKey(Long.valueOf(userIds));
        if (user.getDataState().equals(0)){
            throw new RuntimeException("用户启用状态下不能删除！");
        }
        userRoleMapper.deleteByUserId(userIds);
        userMapper.deleteByPrimaryKey(Long.valueOf(userIds));
    }
}
